import { ChapterContext } from '@/hooks/useChapterContext'
import Typography from '@mui/material/Typography'
import React, { useContext, useEffect, useState } from 'react'

import Accordion from '@mui/material/Accordion'
import AccordionSummary from '@mui/material/AccordionSummary'
import AccordionDetails from '@mui/material/AccordionDetails'
import ExpandMoreSharp from '@mui/icons-material/ExpandMoreSharp'
import BaseNode, { NodeType } from '@/Model/Node/BaseNode'

import Button from '@mui/material/Button'
import ButtonGroup from '@mui/material/ButtonGroup'
import Stack from '@mui/material/Stack'
import localforage, { clear } from 'localforage'
import DecisionNode from '@/Model/Node/DecisionNode'
import { readFile, saveFile } from '@/utils/file'
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'
import ToggleButton from '@mui/material/ToggleButton'


export default function NodeTree(){
  const chapterContext = useContext(ChapterContext)
  const [chapter, setChapter] = chapterContext?.chapter
  const [currentCard, setCurrentCard] = chapterContext.currentCard
  const [_, setRefresh] = chapterContext.refresh
  
  const nodes = chapter.nodes
  const [type, setType] = useState('')
  const nodesKey = Object.keys(chapter.nodes).filter((item:any)=>chapter.nodes[item].type===type || !type)

  const onReadFile = async () => {
    const json = await localforage.getItem('fileCache')
    chapter.toObj(json as JSON)
    setRefresh(new Date().getTime())
  }

  const onSaveFile = () => {
    localforage.setItem('fileCache', chapter.toJSON())
  }

  useEffect(()=>{
    function keyDown(e:any){
      var currKey=0, e=e||event||window.event;
      currKey = e.keyCode||e.which||e.charCode;
      if(currKey == 83 && (e.ctrlKey||e.metaKey)){
        e.preventDefault();
        onSaveFile()
        return false;
      }
    }
    document.onkeydown = keyDown;
  },[])

  const importFile = async()=>{
    const content = await readFile()
    const json = JSON.parse(content)
    chapter.toObj(json as JSON)
    setRefresh(new Date().getTime())
  }

  const exportFile = async()=>{
    const json = JSON.stringify(chapter.toJSON())
    const blob = new Blob([json],{type: "text/plain;charset=utf-8"})
    await saveFile(blob)
    console.log('保存成功')
  }

  const addNode = (t:NodeType) => {
    chapter.addNode(t)
    setRefresh(new Date().getTime())
  }

  const scrollBottom = ()=>{
    const main = document.querySelector('#main')
    let height = main?.scrollHeight as number
    if (main && height-100>window.innerHeight) {
      main.scroll(200, height+200)
    }
  }



  return <div style={{
    height:'100%', 
    width:'30%', 
    background:'#ccc',
    position:'fixed',
    left:0,
    padding:10,
    boxSizing:'border-box'
  }}>
    <Stack direction="row" spacing={2} alignItems="center">
      <Typography variant="h5"> 故事线 </Typography>
      <Typography>节点数量（{Object.keys(chapter.nodes).length}）</Typography>
    </Stack>
    <ButtonGroup style={{ right: 0, marginBottom:10}}>
      <Button onClick={importFile} variant="contained"> 导入 </Button>
      <Button onClick={exportFile} variant="contained"> 导出 </Button>
      <Button onClick={onReadFile} variant="contained"> 打开 </Button>
      <Button onClick={onSaveFile} variant="contained"> 保存 </Button>
      <Button onClick={scrollBottom} variant="contained"> 到底 </Button>
      <Button onClick={() => {addNode('start')}} variant="contained">添加</Button>
    </ButtonGroup>
    <ToggleButtonGroup
      color="primary"
      exclusive value={type} 
      onChange={(v, newAlignment)=>{
        setType(newAlignment)
      }}>
      <ToggleButton value="">全部</ToggleButton>
      <ToggleButton value="decision">选择</ToggleButton>
      <ToggleButton value="common">常规</ToggleButton>
      <ToggleButton value="option">选项</ToggleButton>
    </ToggleButtonGroup>
    <div style={{overflow:'auto', height:'80%'}}>
    {
      nodesKey.map((item:any, index:number)=>(
        <Accordion key={index} onDoubleClick={()=>{
          setCurrentCard(item)
        }}>
          <AccordionSummary expandIcon={<ExpandMoreSharp />} style={{background:currentCard===item?'#0099CC':'#eee'}}>
            <Typography>
              {nodes[item].title}
              {(nodes[item] as DecisionNode)?.question}
            </Typography>
            {nodes[item].type==='option'?<div style={{background:'#ccc', padding:2}}>选项</div>:null}
            {nodes[item].type==='decision'?<div style={{background:'red', padding:2}}>选择</div>:null}
          </AccordionSummary>
          <AccordionDetails>
            <Typography>{nodes[item].desc}</Typography>
            <div>
              <Typography>UUID:</Typography>
              <Typography fontSize={10}>{nodes[item].uuid}</Typography>
            </div>
            <div>
              <Typography>Prev:</Typography>
              <Typography fontSize={10}>{nodes[item].prev}</Typography>
            </div>
            <div>
              <Typography>Next:</Typography>
              <Typography fontSize={10}>{nodes[item].next}</Typography>
            </div>
          </AccordionDetails>
        </Accordion>
      ))
    }
    </div>
    
  </div>
}

